package com.example.mingyue.service.impl;


import ch.qos.logback.core.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mingyue.Exception.LoginFailedException;
import com.example.mingyue.Exception.RegexException;
import com.example.mingyue.Exception.UserException;
import com.example.mingyue.constant.MessageConstant;
import com.example.mingyue.constant.MqConstant;
import com.example.mingyue.constant.WxConstant;
import com.example.mingyue.datasource.DataSource;
import com.example.mingyue.mapper.UserMapper;
import com.example.mingyue.model.dto.UserDto;
import com.example.mingyue.model.dto.UserLoginDto;
import com.example.mingyue.model.entity.User;
import com.example.mingyue.properties.WechatProperties;
import com.example.mingyue.service.UserService;
import com.example.mingyue.utils.HttpClientUtils;
import com.example.mingyue.utils.RegexUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 我自飞扬临天下
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-01-09 12:05:05
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatProperties wechatProperties;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public User userLogin(UserLoginDto userDto) {
        //获取微信用户唯一标识openid
        String openid = getOpenId(userDto);

        if(openid == null){
            //登录失败
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //判断是否未新用户
        User user = userMapper.newUserByOpenId(openid);
        if(user == null){
            //就是新用户,需要添加用户
            User user1 = new User();
            user1.setOpenid(openid);
            user1.setCreateTime(new Date());
            userMapper.addUser(user1);
        }
        return user;
    }

    /**
     * 新增普通用户
     * @param userDto
     */
    @Override
    public void insertUser(UserDto userDto) {

        log.error("接收参数{}",userDto.getPhone());
        //先判断用户是否存在
        QueryWrapper qw = new QueryWrapper();
        qw.eq("phone",userDto.getPhone());
        List<User> users = userMapper.selectList(qw);
        log.error("这里{}",users);
        if(users.size() != 0){
            throw new UserException(MessageConstant.USER_EXIST_ERROR);
        }

        if(RegexUtils.isPhoneInvalid(userDto.getPhone())){
            throw new RegexException(MessageConstant.PHONE_ERROR);
        }
        if(RegexUtils.isPasswordInvalid(userDto.getUserPassword())){
            throw new RegexException(MessageConstant.PASSWORD_ERROR);
        }

        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        //mp添加用户
        userMapper.insert(user);

        System.out.println("发送者rabbit被触发了");
        //mq发送消息给对ES进行数据同步
        rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_INSERT_KEY,user.getId());

    }

    /**
     * 删除普通用户
     * @param id
     */
    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteById(id);

        System.out.println("发送者rabbit被触发了");
        rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_DELETE_KEY,id);
    }

    /**
     * 用户修改信息，暂时用不上,和新增同一个套路
     */
    public void userUpdateInfo(){
        //mq发送消息给对ES进行数据同步
//        rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_INSERT_KEY,user.getId());
    }

    /**
     * 新增同步ES
     * @param id
     */
    @Override
    public void insertUserES(Integer id) {
        try {
            //数据库添加完数据,mq监听获取用户id,查表出来数据后，将数据同步到ES
            User user = userMapper.selectById(id);

            //对密码进行脱敏
            user.setUserPassword(null);

            IndexRequest request = new IndexRequest("mingyue").id(user.getId().toString());
            request.source(JSON.toJSONString(user), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 删除同步ES
     * @param id
     */
    @Override
    public void deleteUserES(Integer id) {

        try {
            DeleteRequest request = new DeleteRequest("mingyue",id.toString());
            client.delete(request,RequestOptions.DEFAULT);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //获取openid
    public String getOpenId(UserLoginDto userDto){
        //map是请求参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",wechatProperties.getAppId());
        map.put("secret",wechatProperties.getAppSecret());
        map.put("js_code",userDto.getCode());
        map.put("grant_type","authorization_code");

        String json = HttpClientUtils.getRequest(WxConstant.WX_LOGIN,map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }





}




